<template>
  <div class="check">
    <el-header>
      <template v-if="isExpanded">
        <el-input
          placeholder="请输入单据编号"
          v-model="queryInfo.billNo"
          clearable
          size="small"
          @clear="handleClearBillNo"
        ></el-input>
        <el-date-picker
          v-model="queryInfo.billDate_begin"
          type="date"
          placeholder="请选择开始日期"
          size="small"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        ></el-date-picker>
        <span>~</span>
        <el-date-picker
          v-model="queryInfo.billDate_end"
          type="date"
          placeholder="请选择结束日期"
          size="small"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        ></el-date-picker>
        <el-input
          placeholder="请输入单据主题"
          v-model="queryInfo.subject"
          clearable
          size="small"
          @clear="handleClearSubject"
        ></el-input>
        <el-select v-model="queryInfo.customerId_dictText" placeholder="请选择客户" size="small">
          <el-option label="请选择客户" value></el-option>
          <el-option label="kunkun" value="customer1"></el-option>
          <!-- 可根据实际情况添加更多客户选项 -->
        </el-select>
        <el-select v-model="queryInfo.billStage" placeholder="请选择单据阶段" size="small">
          <el-option label="请选择单据阶段" value></el-option>
          <el-option label="编制中" value="11"></el-option>
          <el-option label="编制完" value="14"></el-option>
          <el-option label="核批中" value="12"></el-option>
          <el-option label="核批撤销" value="13"></el-option>
          <el-option label="核批完" value="15"></el-option>
          <el-option label="执行中" value="16"></el-option>
          <el-option label="执行止" value="17"></el-option>
          <el-option label="执行完" value="18"></el-option>
        </el-select>
        <el-select v-model="queryInfo.isEffective" placeholder="请选择已生效" size="small">
          <el-option label="请选择已生效" value></el-option>
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
        <el-select v-model="queryInfo.isClosed" placeholder="请选择已关闭" size="small">
          <el-option label="请选择已关闭" value></el-option>
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
        <el-select v-model="queryInfo.isVoided" placeholder="请选择已作废" size="small">
          <el-option label="请选择已作废" value></el-option>
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </template>
      <template v-else>
        <el-input
          placeholder="请输入单据编号"
          v-model="queryInfo.billNo"
          clearable
          size="small"
          @clear="handleClearBillNo"
        ></el-input>
        <el-date-picker
          v-model="queryInfo.billDate_begin"
          type="date"
          placeholder="请选择开始日期"
          size="small"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        ></el-date-picker>
        <span>~</span>
        <el-date-picker
          v-model="queryInfo.billDate_end"
          type="date"
          placeholder="请选择结束日期"
          value-format="YYYY-MM-DD"
          size="small"
          @change="handleDateChange"
        ></el-date-picker>
      </template>
      <el-button type="primary" size="small" @click="getSaleList()" icon="el-icon-search">查询</el-button>
      <el-button size="small" @click="clear()" plain icon="el-icon-refresh-left">重置</el-button>
      <el-button type="success" size="small" @click="showInit()">新增</el-button>
      <el-button type="info" size="small" @click="excel()">导出EXCEL</el-button>
      <el-button
        type="primary"
        size="small"
        @click="dialogVisible = true"
        icon="el-icon-s-tools"
        plain
      >自定义列</el-button>
      <el-button
        size="small"
        @click="toggleInputExpansion"
        :icon="isExpanded? 'el-icon-s-fold' : 'el-icon-s-unfold'"
      ></el-button>
    </el-header>
    <!-- 自定义列弹窗 -->
    <el-dialog title="自定义列" :visible.sync="dialogVisible">
      <el-checkbox-group v-model="checkedColumns">
        <!-- 绑定列对象，label 为列配置对象 -->
        <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col">{{ col.label }}</el-checkbox>
      </el-checkbox-group>
      <el-button @click="confirmColumns">确定</el-button>
    </el-dialog>

    <el-table :data="checkList" border style="width: 100%">
      <!-- 动态生成普通列（索引列除外） -->
      <template v-for="col in checkedColumns">
        <el-table-column
          v-if="col.prop !== 'index'"
          :key="col.prop"
          :label="col.label"
          :width="columns.find(c => c.prop === col.prop).width"
        >
          <template slot-scope="scope">
            <span v-html="scope.row[col.prop] || '-'"></span>
          </template>
        </el-table-column>
      </template>
      <!-- 单独处理索引列（固定在左侧） -->
      <el-table-column
        v-if="checkedColumns.some(col => col.prop === 'index')"
        type="index"
        fixed
        width="50"
        label="#"
      />
      <!-- 操作列固定在右侧，不参与动态生成 -->
      <el-table-column label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加&修改应收管理模态框 -->
    <el-dialog
      :title="checkId ? '销售预售款-新增' : '添加应收管理'"
      :visible.sync="dialogFormVisible"
      width="80%"
    >
      <el-form
        :model="checkForm"
        :rules="rules"
        ref="checkForm"
        label-width="120px"
        class="demo-checkForm"
      >
        <!-- 第一行：单据编号、单据日期、已生效 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="*单据编号" prop="billNo" :required="true">
              <el-input v-model="checkForm.billNo" placeholder="请输入单据编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="*单据日期" prop="billDate" :required="true">
              <el-date-picker
                v-model="checkForm.billDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择单据日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已生效">
              <el-checkbox v-model="checkForm.isEffective" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：已关闭、已作废、生效时间 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="已关闭">
              <el-checkbox v-model="checkForm.isClosed" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="已作废">
              <el-checkbox v-model="checkForm.isVoided" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生效时间">
              <el-date-picker
                v-model="checkForm.effectiveTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择生效时间"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：核批人、审批实例、制单时间 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="核批人" prop="approver">
              <el-select v-model="checkForm.approver" placeholder="请选择核批人">
                <el-option label="请选择" value></el-option>
                <!-- 可根据实际数据添加选项 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审批实例" prop="approvalInstance">
              <el-input v-model="checkForm.approvalInstance" placeholder="请输入审批实例" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单时间" prop="createTime">
              <el-date-picker
                v-model="checkForm.createTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择制单时间"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：制单部门、制单人、修改时间 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="制单部门" prop="createDept">
              <el-select v-model="checkForm.createDept" placeholder="请选择制单部门">
                <el-option label="请选择" value></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单人" prop="creator">
              <el-select v-model="checkForm.creator" placeholder="请选择制单人">
                <el-option label="请选择" value></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="修改时间" prop="updateTime">
              <el-date-picker
                v-model="checkForm.updateTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择修改时间"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行：修改人、自动单据、红字单据 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="修改人" prop="updater">
              <el-select v-model="checkForm.updater" placeholder="请选择修改人">
                <el-option label="请选择" value></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="自动单据" prop="isAuto">
              <el-select v-model="checkForm.isAuto" placeholder="请选择">
                <el-option label="否" value="0"></el-option>
                <el-option label="是" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="红字单据" prop="isRubric">
              <el-select v-model="checkForm.isRubric" placeholder="请选择">
                <el-option label="否" value="0"></el-option>
                <el-option label="是" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 单据主题 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="单据主题" prop="subject">
              <el-input v-model="checkForm.subject" placeholder="请输入单据主题" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 客户和金额 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="*客户" prop="customerId" :required="true">
              <el-select v-model="checkForm.customerId" placeholder="请选择客户">
                <el-option label="请选择客户" value></el-option>
                <el-option label="kunkun" value="customer1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="*金额" prop="amt" :required="true">
              <el-input v-model="checkForm.amt" type="number" placeholder="请输入金额" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 表格区域 -->
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-tabs v-model="activeTab" type="card" style="margin-top: 10px;">
                <el-tab-pane label="销售退货退款申请单" name="sales">
                  <el-table
                    :data="salesOrderList"
                    border
                    style="width: 100%"
                    :footer-method="handleSalesFooter"
                  >
                    <el-table-column type="selection" width="50" />
                    <el-table-column prop="billNo" label="单据编号" sortable />
                    <el-table-column prop="billDate" label="单据日期" sortable />
                    <el-table-column prop="subject" label="单据主题" />
                    <el-table-column prop="srcNo" label="源单号" sortable />
                    <el-table-column prop="customer" label="客户" />
                    <el-table-column prop="saleQty" label="销售数量" width="120">
                      <template slot-scope="scope">
                        <span>{{ scope.row.saleQty || 0 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="saleAmt" label="销售金额" width="120">
                      <template slot-scope="scope">
                        <span>{{ scope.row.saleAmt || 0 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="preReceivable" label="预收余额" width="120">
                      <template slot-scope="scope">
                        <span>{{ scope.row.preReceivable || 0 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="settleQty" label="结算数量" width="120">
                      <template slot-scope="scope">
                        <span>{{ scope.row.settleQty || 0 }}</span>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
                <el-tab-pane label="明细" name="detail">
                  <el-table
                    :data="detailList"
                    border
                    style="width: 100%"
                    :footer-method="handleDetailFooter"
                  >
                    <el-table-column type="selection" width="50" />
                    <el-table-column prop="itemNo" label="* #序号" width="80" />
                    <el-table-column prop="srcNo" label="源单号" />
                    <el-table-column prop="settleMethod" label="结算方式" />
                    <el-table-column prop="fundAccount" label="资金账户" />
                    <el-table-column prop="amount" label="*金额" width="120">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.amount" type="number" placeholder="请输入金额" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" />
                    <el-table-column prop="custom1" label="自定义1" />
                    <el-table-column prop="custom2" label="自定义2" />
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="checkForm.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" v-if="checkId" @click="editForm('checkForm')">修改</el-button>
          <el-button type="success" v-else @click="addCheck('checkForm')">保存</el-button>
          <el-button @click="resetForm('checkForm')">取消</el-button>
          <el-button type="warning" @click="submitAudit()">提交审核</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <Pagination
      :page="queryInfo.pageNo"
      :rows="queryInfo.pageSize"
      :componentTotal="checkTotal"
      @changePage="setPage"
      @changeRows="setRows"
    ></Pagination>
  </div>
</template>

<script>
import { exportExcel } from "../../excelOut/excel.js";
import Pagination from "../../../views/pagination/Pagination.vue";
import axios from "axios";
export default {
  components: {
    Pagination
  },
  data() {
    return {
      activeTab: "sales", // 默认显示销售订单标签
      salesOrderList: [], // 销售订单表格数据
      detailList: [], // 明细表格数据
      queryInfo: {
        _t: null,
        isVoided: 0, // 固定值
        billNo: "",
        billDate_begin: "",
        billDate_end: "",
        subject: "",
        customerId_dictText: "",
        billStage: "",
        isEffective: "",
        isClosed: "",
        isVoided: "",
        column: "createTime", // 固定值
        order: "desc", // 固定值
        field:
          "id,,,billNo,billDate,subject,srcNo,customerId_dictText,opDept_dictText,operator_dictText,amt,checkedAmt,billStage_dictText,isEffective_dictText,isClosed_dictText,isVoided_dictText,isAuto_dictText,isRubric_dictText,remark,effectiveTime,approver_dictText,createTime,createBy_dictText,sysOrgCode_dictText,updateTime,updateBy_dictText", // 固定字段
        pageNo: 1, // 固定页码（根据需求调整）
        pageSize: 10 // 固定每页大小（根据需求调整）
      },
      checkList: [],
      checkTotal: 0,
      dialogFormVisible: false,
      checkId: "",
      checkForm: {
        code: "",
        createBy: "",
        createOn: "",
        createUserId: "",
        modifiedBy: "",
        modifiedOn: "",
        modifiedUserId: "",
        name: "",
        remark: "",
        t: null
      },
      rules: {
        code: [{ required: true, message: "请输入应收编码", trigger: "blur" }],
        name: [{ required: true, message: "请输入应收名称", trigger: "blur" }]
      },
      checkAll: false,
      isIndeterminate: false,
      columns: [
        { prop: "index", label: "#", type: "index", width: 50 },
        { prop: "billNo", label: "单据编号", width: 180 },
        { prop: "billDate", label: "单据日期", width: 150 },
        { prop: "subject", label: "单据主题", width: 150 },
        { prop: "srcNo", label: "源单号", width: 180 },
        { prop: "customerId_dictText", label: "客户", width: 180 },
        { prop: "opDept_dictText", label: "业务部门", width: 150 },
        { prop: "operator_dictText", label: "业务员", width: 150 },
        { prop: "amt", label: "金额", width: 150 },
        { prop: "checkedAmt", label: "已核销金额", width: 150 },
        { prop: "billStage_dictText", label: "单据阶段", width: 150 },
        { prop: "isEffective_dictText", label: "已生效", width: 100 },
        { prop: "isClosed_dictText", label: "已关闭", width: 100 },
        { prop: "isVoided_dictText", label: "已作废", width: 100 },
        { prop: "isAuto_dictText", label: "自动单据", width: 100 },
        { prop: "isRubric_dictText", label: "红字单据", width: 100 },
        { prop: "remark", label: "备注", width: 150 },
        { prop: "effectiveTime", label: "生效时间", width: 180 },
        { prop: "approver_dictText", label: "核批人", width: 150 },
        { prop: "createTime", label: "制单时间", width: 180 },
        { prop: "createBy_dictText", label: "制单人", width: 150 },
        { prop: "sysOrgCode_dictText", label: "制单部门", width: 150 },
        { prop: "updateTime", label: "修改时间", width: 180 },
        { prop: "updateBy_dictText", label: "修改人", width: 150 }
      ],
      visibleColumns: [], // 实际显示的列
      allColumns: [
        { prop: "index", label: "#", checked: true },
        { prop: "billNo", label: "单据编号", checked: true },
        { prop: "billDate", label: "单据日期", checked: true },
        { prop: "subject", label: "单据主题", checked: true },
        { prop: "srcNo", label: "源单号", checked: true },
        { prop: "customerId_dictText", label: "客户", checked: true },
        { prop: "opDept_dictText", label: "业务部门", checked: true },
        { prop: "operator_dictText", label: "业务员", checked: true },
        { prop: "amt", label: "金额", checked: true },
        { prop: "checkedAmt", label: "已核销金额", checked: true },
        { prop: "billStage_dictText", label: "单据阶段", checked: true },
        { prop: "isEffective_dictText", label: "已生效", checked: true },
        { prop: "isClosed_dictText", label: "已关闭", checked: true },
        { prop: "isVoided_dictText", label: "已作废", checked: true },
        { prop: "isAuto_dictText", label: "自动单据", checked: true },
        { prop: "isRubric_dictText", label: "红字单据", checked: true },
        { prop: "remark", label: "备注", checked: true },
        { prop: "effectiveTime", label: "生效时间", checked: true },
        { prop: "approver_dictText", label: "核批人", checked: true },
        { prop: "createTime", label: "制单时间", checked: true },
        { prop: "createBy_dictText", label: "制单人", checked: true },
        { prop: "sysOrgCode_dictText", label: "制单部门", checked: true },
        { prop: "updateTime", label: "修改时间", checked: true },
        { prop: "updateBy_dictText", label: "修改人", checked: true }
      ],
      dialogVisible: false, // 自定义列弹窗显示控制
      checkedColumns: [],
      isExpanded: false
    };
  },
  computed: {},
  watch: {},
  methods: {
    // 销售订单表格合计处理
    handleSalesFooter(store) {
      const columns = store.columns;
      const data = store.data;
      if (data.length === 0) return;
      const sums = {};
      columns.forEach(column => {
        if (
          ["saleQty", "saleAmt", "preReceivable", "settleQty"].includes(
            column.property
          )
        ) {
          sums[column.property] = data.reduce((total, item) => {
            return total + Number(item[column.property]);
          }, 0);
        }
      });
      return sums;
    },
    // 明细表格合计处理
    handleDetailFooter(store) {
      const columns = store.columns;
      const data = store.data;
      if (data.length === 0) return;
      const sums = {};
      columns.forEach(column => {
        if (column.property === "amount") {
          sums[column.property] = data.reduce((total, item) => {
            return total + Number(item[column.property]);
          }, 0);
        }
      });
      return sums;
    },
    // 删除表格明细行
    deleteDetail(row) {
      const index = this.checkForm.detailList.indexOf(row);
      if (index !== -1) {
        this.checkForm.detailList.splice(index, 1);
      }
    },

    // 处理表格选择
    handleSelectionChange(selection) {
      this.checkForm.selectedDetails = selection;
    },
    submitAudit() {
      this.$refs.checkForm.validate(valid => {
        if (valid) {
          // 这里添加提交审核的接口调用逻辑
          this.$message.success("提交审核成功");
          this.dialogFormVisible = false;
        }
      });
    },
    handleDateChange() {},
    // 重新加载数据
    clear() {
      location.reload();
    },
    // 重置单据编号输入框
    handleClearBillNo() {
      this.queryInfo.billNo = "";
    },
    handleClearSubject() {
      this.queryInfo.subject = "";
    },
    // 重置所有查询条件
    handleReset() {
      this.queryInfo.billNo = "";
      this.queryInfo.billDate_begin = "";
      this.queryInfo.billDate_end = "";
      this.queryInfo.subject = "";
      this.queryInfo.customerId_dictText = "";
      this.queryInfo.billStage = "";
      this.queryInfo.isEffective = "";
      this.queryInfo.isClosed = "";
      this.queryInfo.isVoided = "";
    },
    toggleInputExpansion() {
      this.isExpanded = !this.isExpanded;
    },
    confirmColumns() {
      // 无需额外处理，el-checkbox-group 已自动同步 checkedColumns
      this.dialogVisible = false;
    },
    excel() {
      exportExcel(1031, this, "销售退货退款(有申请,红收)数据");
    },
    showInit() {
      this.dialogFormVisible = true;
      this.checkId = "";
      this.checkForm = {
        code: "",
        name: "",
        remark: ""
      };
    },
    // 获取列表
    async getSaleList() {
      const token = localStorage.getItem("token");
      const getSaleListData = async queryInfo => {
        const currentTime = Date.now();
        this.queryInfo._t = currentTime;

        const queryParams = new URLSearchParams(queryInfo).toString();
        const url = `http://api.erp.byesame.com/jeecg-boot/finance/finReceipt/list/1031?${queryParams}`;

        try {
          const response = await axios.get(url, {
            headers: {
              "x-access-token": token
            }
          });
          return response;
        } catch (error) {
          console.error("请求出错:", error);
          throw error;
        }
      };

      try {
        const { data: res } = await getSaleListData(this.queryInfo);
        this.checkList = res.result.records.map(item => ({
          ...item,
          checked: false
        }));
        this.checkTotal = res.result.total;
        this.updateSaleStatus();
      } catch (error) {
        console.error("请求出错:", error);
      }
    },
    // 假设分页组件传递当前页和每页大小
    setRows(val) {
      this.queryInfo.pageSize = val;
      this.getSaleList();
    },
    setPage(val) {
      this.queryInfo.pageNo = val;
      this.getSaleList();
    },
    // 添加应收管理
    async addSale(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return false;
        const addSale = async formData => {
          const token = localStorage.getItem("token");
          const url = "http://8.142.74.15:9091/api/biosample/check/save";
          try {
            const response = await axios.post(url, formData, {
              headers: {
                "x-access-token": token
              }
            });
            return response;
          } catch (error) {
            console.error("请求出错:", error);
            throw error;
          }
        };
        try {
          const { data: res } = await addSale(this.checkForm);
          this.$message.success("添加应收管理成功");
          this.dialogFormVisible = false;
          this.getSaleList();
        } catch (error) {
          console.error("添加应收时出错:", error);
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 修改按钮打开模态框事件
    async handleEdit(row) {
      this.dialogFormVisible = true;
      this.checkId = row.id;
      const t = Date.now();
      const token = localStorage.getItem("token");
      const url = `http://8.142.74.15:9091/api/biosample/check/info/${this.checkId}?t=${t}`;
      try {
        const { data: res } = await axios.get(url, {
          headers: {
            "x-access-token": token
          }
        });
        this.checkForm = res.check;
        this.$message.success("打开编辑页面成功");
      } catch (error) {
        console.error("打开编辑页面出错:", error);
        this.$message.error("打开编辑页面出错");
      }
    },
    // 修改按钮提交表单事件
    editForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return false;
        const editSale = async formData => {
          const token = localStorage.getItem("token");
          const url = "http://8.142.74.15:9091/api/biosample/check/update";
          try {
            const response = await axios.post(url, formData, {
              headers: {
                "x-access-token": token
              }
            });
            return response;
          } catch (error) {
            console.error("请求出错:", error);
            throw error;
          }
        };
        try {
          const { data: res } = await editSale(this.checkForm);
          if (res.code != 0) return this.$message.error("编辑应收管理失败");
          this.$message.success("编辑应收管理成功");
          this.dialogFormVisible = false;
          this.getSaleList();
        } catch (error) {
          console.error("添加应收管理时出错:", error);
        }
      });
    },
    // 删除应收管理
    handleDelete(row) {
      this.$confirm("是否删除该数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteTeam(row);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async deleteTeam(row) {
      const token = localStorage.getItem("token");
      const url = "http://8.142.74.15:9091/api/biosample/check/delete";
      try {
        const res = await axios.post(url, [row.id], {
          headers: {
            "x-access-token": token
          }
        });
        this.$message.success("删除应收成功");
        this.getSaleList();
      } catch (error) {
        console.error("删除应收时出错:", error);
        this.$message.error("删除应收时出错");
      }
    },
    handleSaleAllChange(val) {
      this.checkList.forEach(item => {
        item.checked = val;
      });
      this.updateSaleStatus();
    },
    handleSingleSaleChange() {
      const checkedCount = this.checkList.filter(item => item.checked).length;
      this.checkAll = checkedCount === this.checkList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.checkList.length;
    },
    updateSaleStatus() {
      const checkedCount = this.checkList.filter(item => item.checked).length;
      this.checkAll = checkedCount === this.checkList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.checkList.length;
    },
    async allDetele() {
      const checkedIds = this.checkList
        .filter(item => item.checked)
        .map(item => item.id);
      if (checkedIds.length === 0) {
        return this.$message.warning("请选择要删除的应收");
      }

      // 添加确认弹出框
      await this.$confirm(
        `确定删除选中的 ${checkedIds.length} 条应收？`,
        "删除确认",
        {
          confirmButtonText: "删除",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(async () => {
          // 使用async处理await
          const token = localStorage.getItem("token");
          const url = "http://8.142.74.15:9091/api/biosample/check/delete";
          try {
            const res = await axios.post(url, checkedIds, {
              headers: {
                "x-access-token": token
              }
            });
            this.$message.success(`成功删除 ${checkedIds.length} 条应收`);
            this.getSaleList();
          } catch (error) {
            console.error("批量删除应收时出错:", error);
            this.$message.error(
              `删除失败：${error.response?.data?.msg || "网络错误"}`
            );
          }
        })
        .catch(() => {
          this.$message.info("已取消删除操作");
        });
    }
  },
  created() {
    // 初始化可见列（根据 allColumns 中 checked 为 true 的列）
    this.checkedColumns = this.allColumns.filter(col => col.checked);
  },
  mounted() {
    this.getSaleList();
  }
};
</script>

<style lang="scss" scoped>
html,
body {
  height: 100%;
}
.check {
  height: 100%;
  padding: 20px;
  .el-header {
    height: 32px !important;
    padding: 0;
    display: flex;
    .el-button {
      margin-left: 10px;
    }
    .el-input {
      width: 360px;
    }
  }
  .el-table {
    margin-top: 20px;
    height: 100%;
    overflow: auto;
  }
}
</style>  